package com.cl.unipay4j.ali;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.cl.unipay4j.core.*;
import com.cl.unipay4j.core.util.DateUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 账单下载类
 *
 * @author siashan
 * @since v1.0.1
 **/
@Slf4j
public class AliPayBillDownload extends AbstractAliPay implements IBillDownload {
    public AliPayBillDownload() {
    }

    public AliPayBillDownload(IPayConfig payConfig) {
        super(payConfig);
    }

    /**
     * 下载对账单
     * @param billDate  账单日期 格式 yyyy-MM-dd
     * @return 账单
     */
    @Override
    public Result execDown(String billDate) {
        log.info("AliBillDownload::=>请求到达，账单日期{}", billDate);
        if (!DateUtil.isLegalBillDate(billDate)) {
            return Result.returnFail(UnipayConst.INVALID_BILL_DATE, "账单日期不合法，正确格式为 yyyy-MM-dd");
        }
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizContent("{" +
                "\"bill_type\":\"trade\"," +
                "\"bill_date\":\"" + billDate + "\"" +
                "  }");
        try {
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                String billDownloadUrl = response.getBillDownloadUrl();
                return Result.tradeSuccess(billDownloadUrl);
            } else {
                return Result.returnFail(response.getSubCode(), response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.info("WxBillDownload::=>下载对账单发生异常,账单类型{}", billDate);
        }
        return Result.exception();
    }
}
